package com.lxx.train.common.controller;


import com.lxx.train.common.exception.BusinessException;
import com.lxx.train.common.exception.enums.BusinessExceptionEnum;
import com.lxx.train.common.resp.CommonResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 统一异常处理、数据预处理等
 */
@RestControllerAdvice
public class ControllerExceptionHandler {

    private static final Logger LOG = LoggerFactory.getLogger(ControllerExceptionHandler.class);

    /**
     * 业务异常统一处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    public CommonResp exceptionHandler(BusinessException e) {
        LOG.error("业务异常：{}", e.getE().getMessage());
        CommonResp commonResp = CommonResp.error(e.getE());
        return commonResp;
    }

    /**
     * 校验异常统一处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    public CommonResp exceptionHandler(BindException e) {
        LOG.error("校验异常：{}", e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        CommonResp commonResp = CommonResp.error(BusinessExceptionEnum.PARAM_ERROR);
        return commonResp;
    }


    /**
     * 所有异常统一处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public CommonResp exceptionHandler(Exception e) {
        LOG.error("系统异常：", e);
        CommonResp commonResp = CommonResp.error(BusinessExceptionEnum.INTERNAL_SERVER_ERROR);
        return commonResp;
    }


}

